--
-- Author: shunguo.chen
-- Date: 2016-06-20 20:23:47
--

local string_sub = string.sub
local string_len = string.len
local string_format = string.format

local table_concat = table.concat

local Node_findChild = cc.Node.findChild

-- 代理ui，可以使用 ui.Text_name 获得Text_name节点
-- 1. ui["panel/Text_name"] 搜索 nativeUI/panel 树下面名字为 Text_name 的节点
-- 2. ui.Text_name 搜索 nativeUI 树下面名字为 Text_name 的节点
-- 使用广度优先，搜索到第一个即停止，并且已搜索名字缓存该节点
local _metaTab={
    __index = function(tab, key)
        -- print("key = " .. key)
        local node = Node_findChild(tab.nativeUI, "//"..key)
        rawset(tab, key, node)
        return node
    end
}
local function ui_delegate(nativeUI)
    if(nativeUI == nil)then
        return nil
    end

    local tab = {["nativeUI"] = nativeUI}
    setmetatable(tab, _metaTab)
    return tab
end

function display.uiDelegate(...)
	return ui_delegate(...)
end

local function ui_add_click_listener(ui, f, withMotion, scale, touchFunc, cancelFunc)
    withMotion = withMotion or false
    local initScale = 1
    if withMotion then
        initScale = ui:getScale()
    end
    scale = scale or 0.1
    ui:addTouchEventListener(
        function(sender,eventType)
            if eventType == ccui.TouchEventType.began then
                -- print(sender:getName() .. " widget click began")
                if withMotion then
                    sender:setScale(initScale - scale)
                end
                if nil ~= touchFunc then
                    touchFunc(true)
                end
            elseif eventType == ccui.TouchEventType.canceled then
                -- print(sender:getName() .. " widget click cancel()")
                if withMotion then
                    sender:runAction(cc.ScaleTo:create(0.05, initScale))
                end
                if nil ~= touchFunc then
                    touchFunc(false)
                end
                executeFunc(cancelFunc)
            elseif eventType == ccui.TouchEventType.ended then
                -- print(sender:getName() .. " widget click end")
                if withMotion then
                    sender:runAction(cc.ScaleTo:create(0.05, initScale))
                end
                if nil ~= touchFunc then
                    touchFunc(false)
                end
                f(sender,eventType)
            end
        end
    )
end

function display.uiAddClick(...)
    return ui_add_click_listener(...)
end

-- 为parent的红点设置可见性，不可见需要停止动画，没添加的就不需要再添加
function display.setNewPointVisible(parent, visible)
    if cc.isDead(parent) then return end
    parent:setVisible(visible)

    local flagNode = parent:getChildByName("NEW_FUNCTION_FLAG")
    if flagNode then
        local timeline = flagNode:getTimeline()
        if visible then
            timeline:gotoFrameAndPlay(0, true)
        else
            timeline:gotoFrameAndPause(0)
        end
    else
        if visible then
            display.addNewPoint(parent)
        end
    end
end

-- 为parent添加红点
function display.addNewPoint(parent)
    if cc.isDead(parent) then return end

    local flagNode = parent:getChildByName("NEW_FUNCTION_FLAG")
    if not flagNode then
        local pSize = parent:getContentSize()
        flagNode = cc.CSLoader:createNode(Res.NewFunctionFlagNode,false,true)
        flagNode:setName("NEW_FUNCTION_FLAG")
        parent:addChild(flagNode)
        flagNode:setPosition(cc.p(pSize.width / 2, pSize.height / 2))

        local timeline = flagNode:getTimeline()
        timeline:gotoFrameAndPlay(0, true)
    end

    return flagNode
end

-- 震动
function display.nodeShake(node, conf)
    if node and conf then
        node:stopAllActions()
        local actions = {0,0}
        actions[1] = custom.Shaker:create(
            conf.duration,
            conf.strengthX,
            conf.strengthY,
            conf.interval,
            conf.intervalFactor,
            conf.dampingX,
            conf.dampingXFactor,
            conf.dampingY,
            conf.dampingYFactor)
        actions[2] = cc.Place:create(cc.p(0,0))
        node:runAction(cc.Sequence:create(actions))
    end
end

-- 处理文本加背景的适配，背景会根据文本宽度进行宽度适配
-- tipText  文本
-- bgImg    背景图片
-- gap      文本和背景图片的宽度差
function display.doTipBgLayout(tipText, bgImg, gap)
    if cc.isDead(tipText) then return end
    if cc.isDead(bgImg) then return end

    gap = gap or 66
    local tipSize = tipText:getVirtualRendererSize()
    local bgSize = bgImg:getContentSize()
    bgSize.width = tipSize.width + gap
    bgImg:setContentSize(bgSize)
end

-- 设置btn是否可点击，不可点击会自动灰度处理
--param
--btn       按钮
--enable    是否可点击
function display.setBtnTouchEnable(btn, enable)
    enable = enable or false
    local state
    if enable then
        state = 0
    else
        state = 1
    end
    btn:setTouchEnabled(enable)
    btn:getVirtualRenderer():setState(state)
    btn:setOpacity( enable and 255 or 255 * 0.8 )

end

-- 设置btn是否是灰色的
--btn       按钮
--isGray    是否为灰色
function display.setBtnGray(btn, isGray)
    local state
    if isGray then
        state = 1
    else
        state = 0
    end
    btn:getVirtualRenderer():setState(state)
end

local __drawNode = nil
function display.drawNodeBox(node, color, clear)
    if DEBUG == 0 then return end
    if not __drawNode then
        __drawNode = cc.DrawNode:create()
        cc.Director:getInstance():getRunningScene():addChild(__drawNode, 10000)
    end

    if clear then
        __drawNode:clear()
    end

    if not node then return end
    if tolua.isnull(node) then return end
    color = color or cc.c4f(math.random(),math.random(),math.random(),1)

    local ap = node:getAnchorPoint()
    local pos = cc.p(node:getPosition())
    local rect = node:getBoundingBox()
    local pos_w = node:getParent():convertToWorldSpace(cc.p(rect.x, rect.y))
    -- local pos_w = cc.p(rect.x, rect.y)

    -- dump(ap, "drawNodeBox.ap")
    -- dump(pos, "drawNodeBox.pos")
    -- dump(pos_w, "drawNodeBox.pos_w")
    -- dump(rect, "drawNodeBox.rect")

    local maxX = pos_w.x + rect.width
    local maxY = pos_w.y + rect.height
    __drawNode:drawRect(pos_w, cc.p(maxX, maxY), color)
end

-- 设置 多个nodes居中，传进来的node要保证顺序是从左到右的，并且是同一级别的，node的X方向锚点必须是0.5
-- dot是端点，如果没有就设置为空
-- parentNode是父节点，要保证它的位置是居中的
function display.setNodesMiddle(parentNode, dot, ...)
    if not parentNode then return end
    local nodes = {...}
    local count = #nodes
    if count < 1 or count > 4 then return end -- 暂时限制1-4个node
    local totalLength = 0
    local lengths = {}

    for i = 1, count do
        local node = nodes[i]
        node:setAnchorPointX(0.5)
        lengths[i] = node:getContentSize().width * node:getScaleX()
        totalLength = totalLength + lengths[i]
    end

    local size = parentNode:getContentSize().width
    local interval = 4 --每两个node之间的间距
    totalLength = totalLength + (count - 1) * interval
    if dot then
        dot:setAnchorPointX(0.5)
        dot:setPositionX(size / 2)
        dot:setContentSize(cc.size(totalLength + 40, dot:getContentSize().height))
    end

    local leftLen = 0
    for i = 1, count do
        local rightLen = totalLength / 2 - leftLen - lengths[i]
        local posX = size / 2 - rightLen - lengths[i] / 2
        nodes[i]:setPositionX(posX)

        leftLen = leftLen + lengths[i] + interval
    end

end

-- 设置nodes在其父容器内局左对齐
-- gap 间隔
-- fristNode 第一个node，用来对照，nodes排在其后面；为空nodes从0开始排位置
-- ... 需要排位置的nodes
function display.setNodesLeft(gap, fristNode, ...)
    local nodes = {...}
    if #nodes == 0 then return end
    gap = gap or 5
    local ap, width
    local posX = 0
    if fristNode then
        ap = fristNode:getAnchorPoint()
        width = fristNode:getContentSize2()
        posX = fristNode:getPositionX() + (1 - ap.x) * width
    end

    for i,node in ipairs(nodes) do
        ap = node:getAnchorPoint()
        width = node:getContentSize2()
        posX = posX + ap.x * width + gap
        node:setPositionX(posX)
        posX = posX + (1 - ap.x) * width
    end
end

-- 设置btn在固定时间之后才可以点击，并展示时间变化
-- btn      需设置的按钮
-- timeout  过期时间（s）
-- textName 按钮文本名字，没有使用默认名字（Text/Text_1）
function display.setBtnTimeout(btn, timeout, textName)
    if not btn then return end
    btn:stopActionByTag(201)
    timeout = timeout or 0

    local text = btn:getChildByName(textName or "Text")
    if not text then
        text = btn:getChildByName("Text_1")
    end
    if not text then
        text = btn:getChildByName("name")
    end

    if not text then return end
    if btn._defStr then
        text:setString(btn._defStr)
    else
        btn._defStr = text:getString()
    end

    local function update()
        if timeout > 0 then
            display.setBtnTouchEnable(btn, false)
            text:setString(btn._defStr .. "(" .. timeout .. "s)")
            local act = btn:performWithDelay(update, 1)
            act:setTag(201)
        else
            text:setString(btn._defStr)
            display.setBtnTouchEnable(btn, true)
        end
        timeout = timeout - 1
    end

    update()
end

function display.stopBtnTimeout(btn)
    btn:stopActionByTag(201)

    local text = btn:getChildByName(textName or "Text")
    if not text then
        text = btn:getChildByName("Text_1")
    end
    if not text then
        text = btn:getChildByName("name")
    end
    if not text then return end
    if btn._defStr then
        text:setString(btn._defStr)
    end
end

function display.removeListUnuseItem(list, len)
    local ListViewExtend = require("app.widget.ListViewExtend")
    ListViewExtend.removeUnuseItem(list, len)
end

---------------------------------- timeline start --------------------------------
function display.playTimeline(node, frame, isForever)
    frame = frame or 0
    isForever = isForever or false
    local timeline = node:getTimeline()
    if timeline then
        timeline:gotoFrameAndPlay(frame, isForever)
    end
end

function display.pauseTimeline(node, frame)
    local timeline = node:getTimeline()
    if timeline then
        if frame then
            if frame == "min" then
                frame = 0
            elseif frame == "max" then
                frame = timeline:getDuration()
            end
            timeline:gotoFrameAndPause(frame)
        else
            timeline:pause()
        end
    end
end

function display.resumeTimeline(node)
    local timeline = node:getTimeline()
    if timeline then
        timeline:resume()
    end
end
---------------------------------- timeline end ----------------------------------


---------------------------------- RichText xml start ----------------------------

function display.stringWithColor(color)
    local c = color or cc.c4b(176, 176, 176, 255)   --默认白色
    return string_format("#%02X%02X%02X", c.r, c.g, c.b)
end

-- colorStr = #FF08F5
function display.color3BWithString(colorStr)
    local r = tonumber(string_sub(colorStr, 2, 3), 16)
    local g = tonumber(string_sub(colorStr, 4, 5), 16)
    local b = tonumber(string_sub(colorStr, 6, 7), 16)
    return cc.c3b(r, g, b)
end

-- colorStr = #FF08F5
function display.color4BWithString(colorStr)
    local r = tonumber(string_sub(colorStr, 2, 3), 16)
    local g = tonumber(string_sub(colorStr, 4, 5), 16)
    local b = tonumber(string_sub(colorStr, 6, 7), 16)
    return cc.c4b(r, g, b, 255)
end

-- <font face="" size="" color="">***</font>
function display.getRichTextFontXml(text, color, size, face)
    if text == nil or string_len(text) == 0 then return "" end
    local ary = {"<font"}
    if color then
        ary[#ary + 1] = " color='" .. color .. "'"
    end
    if size then
        ary[#ary + 1] = " size='" .. size .. "'"
    end
    if face then
        ary[#ary + 1] = " face='" .. face .. "'"
    end
    ary[#ary + 1] = ">"
    ary[#ary + 1] = text
    ary[#ary + 1] = "</font>"
    return table_concat(ary)
end

-- <img src="" width="" height="" />
function display.getRichTextImgXml(src, width, height)
    if src == nil or string_len(src) == 0 then return "" end
    local ary = {"<img src='", src, "'"}
    if width then
        ary[#ary+1] = " width='" .. width .. "'"
    end
    if height then
        ary[#ary+1] = " height='" .. height .. "'"
    end
    ary[#ary+1] = " />"
    return table_concat(ary)
end

-- <urlImg src="" width="" height="" />
function display.getRichTextUrlImgXml(src, width, height)
    if src == nil or string_len(src) == 0 then return "" end
    local ary = {"<urlImg src='", src, "'"}
    if width then
        ary[#ary+1] = " width='" .. width .. "'"
    end
    if height then
        ary[#ary+1] = " height='" .. height .. "'"
    end
    ary[#ary+1] = " />"
    return table_concat(ary)
end

-- <csb tag="" src="" width="" height="" />
function display.getRichTextCSBXml(src, tag, width, height)
    if src == nil or string_len(src) == 0 then return "" end
    local ary = {"<csb src='", src, "'"}
    if tag then
        ary[#ary+1] = " tag='" .. tag .. "'"
    end
    if width then
        ary[#ary+1] = " width='" .. width .. "'"
    end
    if height then
        ary[#ary+1] = " height='" .. height .. "'"
    end
    ary[#ary+1] = " />"
    return table_concat(ary)
end

-- <a href="">***</a>
-- params
-- isUnder true/nil   是否加下划线
-- color colorStr   字体颜色
function display.getRichTextUrlXml(text, url, isUnder, color, size)
    if text == nil or string_len(text) == 0 then return "" end
    if color then
        text = display.getRichTextFontXml(text, color, size)
    end
    local ary = {"<a href='", url, "'>", text, "</a>"}
    local ret = table_concat(ary)
    if isUnder then
        ret = display.getRichTextEffectXml(ret, "u")
    end
    return ret
end

-- <b>**</b>            粗体
-- <i>**</i>            斜体
-- <del>**</del>        删除线
-- <u>**</u>            下划线
-- <big>**</big>        变大
-- <small>**</small>    变小
local effectDict = {b=true, i=true, del=true, u=true, big=true, small=true}
function display.getRichTextEffectXml(text, effectType)
    if text == nil or string_len(text) == 0 then return "" end
    if effectDict[effectType] then
        local ary = {"<", effectType, ">", text, "</", effectType, ">"}
        text = table_concat(ary)
    end
    return text
end
---------------------------------- RichText xml end ----------------------------


local EventDispatcher = cc.Director:getInstance():getEventDispatcher()

--node 添加 EventListenerTouchOneByOne 通用范式
function display.nodeTouchOneByOne(node, beganCB, endCB, isSwallow, moveCB, cancelCB)
    isSwallow = isSwallow or false

    local function touchBegan(touch, event)
        local posX,posY = touch:getLocation()
        -- dump(pos, "touchBegan pos")
        if beganCB then
            return beganCB(posX,posY)
        else
            return false
        end
    end

    local function touchMoved(touch, event)
        local posX,posY = touch:getLocation()
        -- dump(pos, "touchMove pos")
        executeFunc(moveCB, posX,posY)
    end

    local function touchEnded(touch, event)
        local posX,posY = touch:getLocation()
        -- dump(pos, "touchEnd pos")
        executeFunc(endCB, posX,posY)
    end

    local function touchCanceled(touch, event)
        local posX,posY = touch:getLocation()
        executeFunc(cancelCB, posX,posY)
    end

    local listener = cc.EventListenerTouchOneByOne:create()
    listener:setSwallowTouches(isSwallow)
    listener:registerScriptHandler(touchBegan,cc.Handler.EVENT_TOUCH_BEGAN)
    listener:registerScriptHandler(touchMoved,cc.Handler.EVENT_TOUCH_MOVED)
    listener:registerScriptHandler(touchEnded,cc.Handler.EVENT_TOUCH_ENDED)
    listener:registerScriptHandler(touchCanceled,cc.Handler.EVENT_TOUCH_CANCELLED)
    EventDispatcher:addEventListenerWithSceneGraphPriority(listener, node)
    return listener
end

-- 为node添加touch事件，touch不在node.boundingBox内部，则执行endCB or 移除node
--param
--node      目标node
--endCB     touchEndFunc
--isSwallow 吞噬点击事件
function display.nodeRemoveForNotHit(node, endCB, isSwallow)
    local function touchBegan(posX,posY)
        return not node:hitTest(posX,posY)
    end

    local function touchEnded(posX,posY)
        if not node:hitTest(posX,posY) then
            if endCB then
                executeFunc(endCB, posX,posY)
            else
                node:removeFromParent()
            end
        end
    end

    return display.nodeTouchOneByOne(node, touchBegan, touchEnded, isSwallow)
end

-- 为一组node添加touch事件，touch不在组中所有node.boundingBox内部，则执行endCB or 移除node
--param
--nodeList  目标node组
--endCB     touchEndFunc
--isSwallow 吞噬点击事件
function display.nodeListRemoveForNotHit(nodeList, endCB, isSwallow)
    local function touchBegan(posX,posY)
        local flag = true
        for _,v in pairs(nodeList) do
            flag = flag and ( not v:hitTest(posX,posY) )
        end
        return flag
    end

    local function touchEnded(posX,posY)
        local flag = true
        for _,v in pairs(nodeList) do
            flag = flag and ( not v:hitTest(posX,posY) )
        end
        if flag then
            if endCB then
                executeFunc(endCB, posX,posY)
            else
                for _,v in pairs(nodeList) do
                    v:removeFromParent()
                end
            end
        end
    end
    local ndoeTemp = nodeList[1]
    return display.nodeTouchOneByOne(ndoeTemp, touchBegan, touchEnded, isSwallow)
end

-- 为node添加touch事件
--param
--node      目标node
--endCB     touchEndFunc
--isSwallow 吞噬点击事件
function display.nodeTouchForHit(node, endCB, isSwallow)
    local function touchBegan(posX,posY)
        return node:hitTest(posX,posY)
    end

    local function touchEnded(posX,posY)
        if node:hitTest(posX,posY) then
            executeFunc(endCB, posX,posY)
        end
    end

    return display.nodeTouchOneByOne(node, touchBegan, touchEnded, isSwallow)
end

-- node位置根据 boundingBox 自适配位置
-- distanceX 两者X间距
-- distanceY 两者Y间距
function display.adjustNodePos( boundingBox, node, distanceX, distanceY )
    if not boundingBox or not node then return end

    distanceX = distanceX or 0 -- 默认0
    distanceY = distanceY or 0 -- 默认0
    local nodeWidth, nodeHeight = node:getContentSize2()
    -- print( " ----------->>>> " .. distanceX .. " ; " .. nodeWidth .. " ; " .. nodeHeight )

    local posX = 0
    local posY = 0
    if boundingBox.x < display.width/2 then -- 屏幕左半区？右展开
        posX = boundingBox.x + boundingBox.width + distanceX
    else
        posX = boundingBox.x - distanceX - nodeWidth
    end

    posY = boundingBox.y  + boundingBox.height + distanceY - nodeHeight
    if 10 > posY then -- 下方越界了？
        posY = 10
    end

    -- dump( boundingBox, " ----------->>>> adjustNodePos " .. posX .. " ; " .. posY )
    node:setPositionX( posX )
    node:setPositionY( posY )
end


-- 动态适配一组节点X位置
-- 注意nodesList不可为hashTable
function display.autoAdjustNodesPosX( panelWidth, nodesList, showNum, distanceX )
    if 0 >= showNum or 0 >= #nodesList then return end -- 无内容不处理


    local itemMiddlePosX = panelWidth/2
    local itemWidth = nodesList[1]:getContentSize2()
    local anchorX = nodesList[1]:getAnchorPoint().x
    local deltalX = (anchorX - 0.5) * itemWidth
    local distanceX = distanceX or nodesList[2]:getPositionX() - nodesList[1]:getPositionX() - itemWidth

    if 1 >= showNum then -- 对于只有一个可见node
        nodesList[1]:setPositionX( itemMiddlePosX + deltalX)
        return
    end

    -- print( " ------------>>>>> 参数 ", itemMiddlePosX, itemWidth, distanceX, showNum )
    if 0 == showNum%2 then -- 偶数个可见
        local leftMid = showNum/2 -- 左侧标记item
        local leftMidPosX = itemMiddlePosX - ( itemWidth + distanceX ) / 2 -- 左侧标记item坐标X
        nodesList[leftMid]:setPositionX( leftMidPosX + deltalX)
        for i = leftMid - 1, 1, -1 do
            local posTemp = leftMidPosX - ( itemWidth + distanceX ) * ( leftMid - i )
            nodesList[i]:setPositionX( posTemp + deltalX)
        end

        local rightMid = showNum/2 + 1 -- 右侧标记item
        local rightMidPosX = itemMiddlePosX + ( itemWidth + distanceX ) / 2 -- 右侧标记item坐标X
        nodesList[rightMid]:setPositionX( rightMidPosX + deltalX)
        for i = rightMid + 1, showNum do
            local posTemp = rightMidPosX + ( itemWidth + distanceX ) * ( i - rightMid )
            nodesList[i]:setPositionX( posTemp + deltalX)
        end
    else
        local midNum = ( showNum + 1 ) / 2
        nodesList[midNum]:setPositionX( itemMiddlePosX + deltalX)
        for i = midNum - 1, 1, -1 do
            local posTemp = itemMiddlePosX - ( itemWidth + distanceX ) * ( midNum - i )
            nodesList[i]:setPositionX( posTemp + deltalX)
        end
        for i = midNum + 1, showNum do
            local posTemp = itemMiddlePosX + ( itemWidth + distanceX ) * ( i - midNum )
            nodesList[i]:setPositionX( posTemp + deltalX)
        end
    end
end

function display.createUpdateAction(callback, interval)
	if not interval then
		interval = 0.5
	end
	local delay = cc.DelayTime:create(interval)
    local sequence = cc.Sequence:create(delay, cc.CallFunc:create(function()

        if callback then
			callback()
		end
    end))
    local action = cc.RepeatForever:create(sequence)
    return action
end


function display.replaceNodeToMultipleLayerNode(srcNode)
    local mulNode = custom.MultipleLayersNode:create()
    if cc.isDead(srcNode) then
        print(" display.replaceNodeToMultipleLayerNode not is nil")
        return mulNode
    end
    mulNode:copyProp(srcNode)
    local children = srcNode:getChildren()
    for _, child in ipairs(children) do
        child:retain()
        child:removeFromParent(false)
        mulNode:addChild(child)
        child:release()
    end
    return mulNode
end


function display.cloneWidget(widget)
    local cloneW = widget:clone()
    local action = widget:getTimeline()
    if action ~= nil then
        local newAction = action:clone()
        cloneW:runAction(newAction)
    end
    return cloneW
end

function display.createMultipleLayerRender(widget, isMultipleLayerNode)
    if not widget then
        return
    end
    local panelNode = widget:getChildByName('Panel')
    assert(panelNode ~= nil, "display.createMultipleLayerRender must have Panel child")
    panelNode:removeFromParent(false)
    if isMultipleLayerNode then
        panelNode = display.replaceNodeToMultipleLayerNode(panelNode)
    end
    -- copy 动画
    local action = widget:getTimeline()
    if action ~= nil then
        local newAction = action:clone()
        panelNode:runAction(newAction)
    end
    return panelNode
end

function display.createMultipleLayerRenderWithCsbPath (csbPath, isMultipleLayerNode)
    local widget = cc.CSLoader:createNode(csbPath)
    return display.createMultipleLayerRender(widget, isMultipleLayerNode)
end

function display.showFunctionNotOpenDetail(funcId)
    if not funcId then
        return
    end
    -- 服务器动态关闭
    if UD:isFeatureClosedByServer(funcId) then
		display.pushToast(L("tips_1110010"))
		return
	end	
    local featureonConf = nil	
    featureonConf = GD:queryFeatureOnById( funcId )
    if featureonConf then
        if featureonConf.questId and "" ~= featureonConf.questId then -- 依赖任务？
            if UD:isMainTaskFinished( featureonConf.questId ) then -- 任务完成？
                local str = string.format( L("lua_code_text_222"), featureonConf.level or 0)
                display.pushToast( str )
            else
                local taskConf =  GD:queryTaskById( featureonConf.questId )
                local str = string.format( L("afterFinishTask"), L(taskConf.name) )
                display.pushToast( str )
            end
        elseif featureonConf.level and "" ~= featureonConf.level then -- 依赖等级开启
            local str = string.format( L("lua_code_text_222"), featureonConf.level )
            display.pushToast( str )
        else
            display.pushToast( L("lua_code_text_458") )
        end
    else
        display.pushToast( L("lua_code_text_458") )
    end
end

-- 来源跳转帮助函数
function display.resourceGotoFeature(data)
    -- dump( data, " ------------->>>> resourceGotoFeature " )
    if data then
        local funcId = tonumber( data.feature )
        if not funcId then return end
        local param = data.param -- param={1:itemID, 2:tabIdx}
        if funcId == Constant.FUNC_TYPE_SHOP then -- 商城
            local shopIndex = param and tonumber(param[1])
            local itemType = param and tonumber(param[2])
            local itemId = param and tonumber(param[3])
            if shopIndex then
                local params = {
                    id = funcId,
                    mode = "open",
                    tabKey = Constant.FUNC_TYPE_SHOP,
                    shopIndex = shopIndex,
                    itemType = itemType,
                    itemId = itemId
                }
                UIHandler:handleMessage( params )
            else
                UIHandler:handleMessage( { id = funcId, mode = "open" } )
            end
        elseif funcId == Constant.FUNC_TYPE_SHOPDRAW then --奇迹卡片
            local shopIndex = param and tonumber(param[1])
            if shopIndex then
                UIHandler:handleMessage( { id = funcId, mode = "open", shopIndex = shopIndex } )
            else
                UIHandler:handleMessage( { id = funcId, mode = "open" } )
            end
        elseif funcId == Constant.FUNC_TYPE_RECHARGE then -- 充值
            UIHandler:handleMessage( { id = funcId, mode = "open"} )
        elseif funcId == Constant.FUNC_TYPE_TEAMMATCHING_TEAM 
                or funcId == Constant.FUNC_TYPE_TEAMMATCHING_SPEED  
                or funcId == Constant.FUNC_TYPE_TEAMMATCHING_LEGION then --地下城小队模式/竞速模式/团队模式
            local targetId = param and tonumber(param[1])
            if targetId then
                UIHandler:handleMessage( { id = funcId, mode = "open" , targetId = targetId} )
            else
                UIHandler:handleMessage( { id = funcId, mode = "open" } )
            end
        elseif funcId == Constant.FUNC_TYPE_TEAMMATCHING then -- 组队查找器
            local targetId = param and tonumber(param[1])
            if targetId then
                UIHandler:handleMessage( { id = funcId, mode = "open" , data = {targetId = targetId}} )
            else
                UIHandler:handleMessage( { id = funcId, mode = "open" } )
            end
        elseif (funcId >= Constant.FUNC_SHOP_FAME_1 and funcId <= Constant.FUNC_SHOP_FAME_99) 
                or funcId == Constant.FUNC_SHOP_HEROMEDAL 
                or funcId == Constant.FUNC_SHOP_BRIGHTMEDAL 
                or funcId == Constant.FUNC_SHOP_ALLMEDAL 
                or funcId == Constant.FUNC_SHOP_ACHIEVEMENT
                or funcId == Constant.FUNC_TYPE_CS_SHOP then --声望商店/英雄徽章商店/光芒徽章商店/成就商店
            local itemType = param and tonumber(param[1])
            local itemId = param and tonumber(param[2])
            if itemType and itemId then
                UIHandler:handleMessage( {id = funcId, mode = "open", itemType = itemType, itemId = itemId} )
            else
                UIHandler:handleMessage( {id = funcId, mode = "open"} )
            end
        elseif funcId == Constant.FUNC_TYPE_COMPOUND then -- 制造
            local lifeSkillId, lifeLevelId
            local formulaId = param and tonumber(param[1])
            local config = GD:queryFormulaById(formulaId)
            if config then
                lifeSkillId = tonumber(config.subkey)
                lifeLevelId = tonumber(config.showType)
            end
            if param then
                UIHandler:handleMessage( {id = funcId, mode = "open", lifeId = lifeSkillId, levelId = lifeLevelId, formulaId = formulaId} )
            else
                UIHandler:handleMessage( {id = funcId, mode = "open"} )
            end
        elseif funcId == Constant.FUNC_TYPE_GANG then -- 公会
            local tabIdx = param and tonumber(param[1])
            local itemType, itemId
            if tabIdx == 5 then -- 公会商店
                itemType = tonumber(param[2])
                itemId = tonumber(param[3])
            end
            if tabIdx then
                UIHandler:handleMessage( {id = funcId, mode = "open", tabIdx = tabIdx, itemType = itemType, itemId = itemId} )
            else
                UIHandler:handleMessage( {id = funcId, mode = "open"} )
            end
        elseif funcId == Constant.FUNC_TYPE_AUCTION_SHOP then -- 拍卖行
            local tabIdx = param and tonumber(param[1])
            local auctionType = param and tonumber(param[2])
            local searchName = param[3]
            if tabIdx then
                UIHandler:handleMessage( {id = funcId, mode = "open", tabIdx = tabIdx, auctionType = auctionType, searchName = searchName} )
            else
                UIHandler:handleMessage( {id = funcId, mode = "open"} )
            end
        elseif funcId == Constant.FUNC_TYPE_MERCENARY then -- 随从
            local partnerId = param and tonumber(param[2])
            if partnerId then
                UIHandler:handleMessage( {id = funcId, mode = "open", partnerId = partnerId} )
            else
                UIHandler:handleMessage( {id = funcId, mode = "open"} )
            end
        elseif funcId == Constant.FUNC_TYPE_DYNASTY_BATTLE then -- 公会战
            local subData = param and tonumber(param[1])
            if subData then
                UIHandler:handleMessage({id = funcId, mode = "open", subData = subData})
            else
                UIHandler:handleMessage( {id = funcId, mode = "open"} )
            end
        elseif funcId == Constant.FUNC_TYPE_ACTIVITY then -- 指南
            local subKey = param and tonumber(param[1])
            if subKey then
                UIHandler:handleMessage({id = funcId, mode = "open", subKey = subKey})
            else
                UIHandler:handleMessage({id = funcId, mode = "open"})
            end
        elseif funcId == Constant.FUNC_TYPE_REWARD_TRACE3 then -- 首充大礼(首充大礼的featureonID不固定只能特殊处理)
            local RewardModel = app:getInst("RewardModel")
            local info = RewardModel:getWelfareActivityBySubType(Enums.ActivitySubType.FirstRecharge)
            if info then
                app:sendMsg("RewardController", "openView", info)
            else
                display.pushToast(L("tips_1110010"))
            end
        elseif funcId == Constant.FUNC_TYPE_CS_GUILD_WAR then
            if not param then
                param = {}
            end
            UIHandler:handleMessage( { id = funcId, mode = "open" , secondTabIndex = tonumber(param[1]), other = tonumber(param[2])} )
        elseif funcId == Constant.FUNC_TYPE_CS_ELITEMATCH then
            UIHandler:handleMessage( { id = funcId, mode = "open" , secondTabIndex = tonumber(param[1])} )
        else
            UIHandler:handleMessage( { id = funcId, mode = "open" } )
        end
    end
end


